package com.shwread.android.ui.widget.sortlistview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.shwread.android.qysw10000227.R;

import java.util.ArrayList;
import java.util.List;

import logic.bean.ContactInfo;
import logic.util.Util;


public class SortAdapter
        extends
        BaseAdapter
        implements
        SectionIndexer
{
	private List<ContactInfo> list = null;
	private Context           mContext;
	private CheckBox          checkAll;
	private int               mark;
	
	private stringList        uids = new stringList();
	
	private onClickMember     listener;
	
	public SortAdapter(Context mContext, List<ContactInfo> list, CheckBox checkAll, onClickMember listener, int mark) {
		this.checkAll = checkAll;
		this.mContext = mContext;
		this.list = removeRepeatContact(list);
		this.listener = listener;
		this.mark = mark;
		if (mark == 1) checkAllListener();
	}
	
	private void checkAllListener() {
		checkAll.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v) {
				selectAll(((CheckBox) v).isChecked());
			}
		});

	}
	
	/**
	 * 当ListView数据发生变化时,调用此方法来更新ListView
	 *
	 * @param list
	 */
	public void updateListView(List<ContactInfo> list) {
		this.list = removeRepeatContact(list);
		notifyDataSetChanged();
	}
	
	private List<ContactInfo> removeRepeatContact(List<ContactInfo> list) {
		if (list == null || list.size() == 0) return list;
		List<ContactInfo> newList = new ArrayList<>();
		for (ContactInfo info : list) {
			boolean isRepeat = false;
			if (newList.size() > 0)
			{
				for (ContactInfo newInfo : newList) {
					if (info.getAccId().equals(newInfo.getAccId()))
					{
						isRepeat = true;
						break;
					}
				}
			}
			if (!isRepeat)
			{
				newList.add(info);
			}
		}
		return newList;
	}

	public int getCount() {
		return this.list.size();
	}
	
	public Object getItem(int position) {
		return list.get(position);
	}
	
	public long getItemId(int position) {
		return position;
	}
	
	public View getView(final int position, View view, ViewGroup arg2) {
		ViewHolder viewHolder = null;
		final ContactInfo mContent = list.get(position);
		if (view == null)
		{
			viewHolder = new ViewHolder();
			view = LayoutInflater.from(mContext).inflate(R.layout.new_interaction_create_team_chose_item, arg2, false);
			viewHolder.cbTitle = (CheckBox) view.findViewById(R.id.title);
			viewHolder.cbLetter = (CheckBox) view.findViewById(R.id.catalog);
			viewHolder.tvLetter = (TextView) view.findViewById(R.id.tv_catalog);
			viewHolder.tvTitle = (TextView) view.findViewById(R.id.tv_title);
			view.setTag(viewHolder);
		}
		else
		{
			viewHolder = (ViewHolder) view.getTag();
		}
		if (mark == 1)
		{
			viewHolder.cbTitle.setVisibility(View.VISIBLE);
			viewHolder.cbLetter.setVisibility(View.VISIBLE);
			viewHolder.tvLetter.setVisibility(View.GONE);
			viewHolder.tvTitle.setVisibility(View.GONE);
			// 根据position获取分类的首字母的Char ascii值
			int section = getSectionForPosition(position);

			// 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
			if (position == getPositionForSection(section))
			{
				viewHolder.cbLetter.setVisibility(View.VISIBLE);
				viewHolder.cbLetter.setText(mContent.getSortLetters());
				viewHolder.cbLetter.setChecked(getCheckStateForSection(section));
				viewHolder.cbLetter.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v) {
						if (((CheckBox) v).isChecked())
						{
							setCheckStateForSection(((CheckBox) v).getText().toString().charAt(0), true);
						}
						else
						{
							setCheckStateForSection(((CheckBox) v).getText().toString().charAt(0), false);
						}

					}
				});
			}
			else
			{
				viewHolder.cbLetter.setVisibility(View.GONE);
				viewHolder.cbLetter.setChecked(false);
			}

			viewHolder.cbTitle.setOnCheckedChangeListener(new OnCheckedChangeListener()
			{

				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
					if (isChecked)
					{
						if (!uids.contains(list.get(position)))
						{
							uids.add(list.get(position));
						}
					}
					else
					{
						uids.remove(list.get(position));
					}
					notifyDataSetChanged();
				}
			});
			if (uids.contains(list.get(position)))
			{
				viewHolder.cbTitle.setChecked(true);
			}
			else
			{
				viewHolder.cbTitle.setChecked(false);
			}
			if (Util.isNotEmpty(this.list.get(position).getStaffName()))
			{
				viewHolder.cbTitle.setText(this.list.get(position).getStaffName());
			}
			else if (Util.isNotEmpty(this.list.get(position).getNickName()))
			{
				viewHolder.cbTitle.setText(this.list.get(position).getNickName());
			}
			else
			{
				viewHolder.cbTitle.setText(this.list.get(position).getAccount());
			}
		}
		else
		{
			viewHolder.cbTitle.setVisibility(View.GONE);
			viewHolder.cbLetter.setVisibility(View.GONE);
			viewHolder.tvLetter.setVisibility(View.VISIBLE);
			viewHolder.tvTitle.setVisibility(View.VISIBLE);
			// 根据position获取分类的首字母的Char ascii值
			int section = getSectionForPosition(position);

			// 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
			if (position == getPositionForSection(section))
			{
				viewHolder.tvLetter.setVisibility(View.VISIBLE);
				viewHolder.tvLetter.setText(mContent.getSortLetters());
				//				viewHolder.tvLetter.setOnClickListener(new OnClickListener()
				//				{
				//					@Override
				//					public void onClick(View v) {
				//						if (((CheckBox) v).isChecked())
				//						{
				//							setCheckStateForSection(((CheckBox) v).getText().toString().charAt(0), true);
				//						}
				//						else
				//						{
				//							setCheckStateForSection(((CheckBox) v).getText().toString().charAt(0), false);
				//						}
				//
				//					}
				//				});
			}
			else
			{
				viewHolder.tvLetter.setVisibility(View.GONE);
				//				viewHolder.tvLetter.setChecked(false);
			}
			viewHolder.tvTitle.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v) {
					listener.onClick(list.get(position));
				}
			});
			//			viewHolder.tvTitle.setOnCheckedChangeListener(new OnCheckedChangeListener()
			//			{
			//
			//				@Override
			//				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			//					if (isChecked)
			//					{
			//						if (!uids.contains(list.get(position)))
			//						{
			//							uids.add(list.get(position));
			//						}
			//					}
			//					else
			//					{
			//						uids.remove(list.get(position));
			//					}
			//					notifyDataSetChanged();
			//				}
			//			});
			//			if (uids.contains(list.get(position)))
			//			{
			//				viewHolder.cbTitle.setChecked(true);
			//			}
			//			else
			//			{
			//				viewHolder.cbTitle.setChecked(false);
			//			}
			if (Util.isNotEmpty(this.list.get(position).getStaffName()))
			{
				viewHolder.tvTitle.setText(this.list.get(position).getStaffName());
			}
			else if (Util.isNotEmpty(this.list.get(position).getNickName()))
			{
				viewHolder.tvTitle.setText(this.list.get(position).getNickName());
			}
			else
			{
				viewHolder.tvTitle.setText(this.list.get(position).getAccount());
			}
		}

		return view;

	}
	
	/**
	 * 根据ListView的当前位置获取分类的首字母的Char ascii值
	 */
	public int getSectionForPosition(int position) {
		return list.get(position).getSortLetters().charAt(0);
	}
	
	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < getCount(); i++)
		{
			String sortStr = list.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) { return i; }
		}

		return -1;
	}
	
	/**
	 * 根据分类的首字母的Char ascii值选择所有该首字母的item
	 *
	 * @param sate
	 *            true:添加(选中) false:删除(未选中)
	 */
	public void setCheckStateForSection(int section, boolean state) {
		for (int i = 0; i < getCount(); i++)
		{
			String sortStr = list.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section)
			{
				if (state)
				{
					uids.add(list.get(i));
				}
				else
				{
					uids.remove(list.get(i));
				}
			}
		}
		this.notifyDataSetChanged();
	}
	
	/**
	 * 根据分类的首字母的判断该首字母里所有Item是否全部选中
	 */
	public boolean getCheckStateForSection(int section) {
		for (int i = 0; i < getCount(); i++)
		{
			String sortStr = list.get(i).getSortLetters();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section)
			{
				if (!uids.contains(list.get(i))) return false;
			}
		}
		return true;
	}
	
	@Override
	public Object[] getSections() {
		return null;
	}
	
	/**
	 * @return 获取所选的uids
	 */
	public List<ContactInfo> getSelectUids() {
		return uids.uidList;
	}
	
	/**
	 * 选择货取消所有item
	 */
	private void selectAll(boolean state) {
		for (ContactInfo contactInfo : list)
		{
			if (state)
			{
				uids.add(contactInfo);
			}
			else
			{
				uids.remove(contactInfo);
			}
		}
		notifyDataSetChanged();
	}
	
	private boolean getCheckAllState() {

		for (ContactInfo contactInfo : list)
		{
			if (!uids.contains(contactInfo)) { return false; }
		}
		return true;
	}
	
	@Override
	public void notifyDataSetChanged() {
		checkAll.setChecked(getCheckAllState());
		super.notifyDataSetChanged();

	}
	
	public interface onClickMember
	{
		void onClick(ContactInfo contactInfo);
	}
	
	final static class ViewHolder
	{
		CheckBox cbLetter;
		CheckBox cbTitle;
		TextView tvLetter, tvTitle;
	}
	
	private class stringList
	{
		ArrayList<ContactInfo> uidList = new ArrayList<ContactInfo>();

		public void add(ContactInfo uid) {
			if (!contains(uid))
			{
				uidList.add(uid);
			}
		}

		public boolean contains(ContactInfo uid) {
			for (ContactInfo u : uidList)
			{
				if (u.getStaffId().equals(uid.getStaffId())) return true;
			}
			return false;
		}

		public boolean remove(ContactInfo uid) {
			for (int i = 0; i < uidList.size(); i++)
			{
				if (uidList.get(i).equals(uid))
				{
					uidList.remove(i);
					return true;
				}

			}
			return false;
		}

	}
}
